package com.zhangye.test.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zhangye.test.entity.EasyArResult;
import com.zhangye.test.mapper.CompanyMapper;
import com.zhangye.test.model.Company;
import com.zhangye.test.util.PageInfo;
import com.zhangye.test.util.cloudUtils;

@Service
public class CompanyService {

	@Autowired
	private CompanyMapper companyMapper;

	@Transactional
	public void updateStatus(Company c){
		int active = c.getActive();
		if(active != -1 && active != 1){
			try {//更新视频
				EasyArResult er = cloudUtils.updateCloud(c.getTargetId(), encode(c.getVideoUrl().getBytes()));
				//更新数据库
				String status = er.getStatusCode();
				if("0".equals(status)){
					String where = " and update_date < now() and target_id = '" + c.getTargetId() + "' and id != " + c.getId();
					List<Company> list = companyMapper.selectByWhere(where);
					if(list.size() > 0){
						companyMapper.updateBatch(list);
					}
					c.setActive(1);
					companyMapper.updateByPrimaryKey(c);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	
	public int deleteByWhere(String where){
		int i = companyMapper.deleteByWhere(where);
		return i;
	}

	
	public int deleteByPrimaryKey(Integer id){
		int i = companyMapper.deleteByPrimaryKey(id);
		return i;
	}
	

	
	public int updateByPrimaryKey(Company c){
		int i = companyMapper.updateByPrimaryKey(c);
		return i;
	}
	public int updateBatch(List<Company> list){
		int i = companyMapper.updateBatch(list);
		return i;
	}

	
	public Company selectByPrimaryKey(Integer cId){
		Company c = companyMapper.selectByPrimaryKey(cId);
		return c;
	}
	
	public List<Company> selectByWhere(String where){
		List<Company> list = companyMapper.selectByWhere(where);
		return list;
	}
	
	
	public int insert(Company c){
		int i = companyMapper.insert(c);
		return i;
	}

	
	/**
	 * 列表
	 * 作者： 张叶
	 * 创建时间：2018年5月23日  上午9:05:40
	 */
	public List<Map<String,Object>> selectByPage(PageInfo pageInfo, String where, String order) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("myCount", pageInfo.getCount());
		param.put("pageSize", pageInfo.getPageSize());
		param.put("page", pageInfo.getPage());
		param.put("where", where);
		param.put("order", order);
		List<Map<String, Object>> m = companyMapper.selectByPage(param);
		pageInfo.setCount(Integer.parseInt(param.get("myCount").toString()));
		return m;
	}

	
	public static String encode(final byte[] bytes) {  
		return new String(Base64.encodeBase64(bytes));  
	}	
}
